import { loginApi, getUserInfoApi } from "@/api/user"
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { Message } from "element-ui";
const state = {
  token: getToken(),
  userId: '',
  avatar: '',
  roles: null, // 
  isRenterPay: '',
  phone: '',
  username: '',
  devicesNum: '',
  payWay: '',
  lowestPrice: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  setUserId: (state, userId) => {
    state.userId = userId
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_PAYWAY: (state, payWay) => {
    state.payWay = payWay
  },
  setRenterPay: (state, isRenterPay) => {
    state.isRenterPay = isRenterPay
  },
  setPhone: (state, phone) => {
    state.phone = phone
  },
  setLowPrice: (state, lowestPrice) => {
    state.lowestPrice = lowestPrice
  },
  SET_USERNAME: (state, username) => {
    state.username = username ? username : '管理员'
  },
  setDeviceNum: (state, devicesNum) => {
    state.devicesNum = devicesNum
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      loginApi(userInfo).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.tokenValue)
        setToken(data.tokenValue)
        Message({
          message: "登录成功",
          type: "success",
          duration: 2 * 1000,
        });
        resolve()
      }).catch(error => {
        Message({
          message: "登录失败！",
          type: "error",
          duration: 2 * 1000,
        });
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfoApi().then(response => {
        const { data } = response
        if (!data) {
          reject('获取失败，请重新登录')
        }
        const { userName, hasUserImage, payWay, userId, devicesNum, lowestPrice, phone, isRenterPay } = data
        commit('SET_USERNAME', userName)
        commit('SET_AVATAR', hasUserImage)
        commit('SET_PAYWAY', payWay)
        commit('setUserId', userId)
        commit('setDeviceNum', devicesNum)
        commit('setLowPrice', lowestPrice)
        commit('setPhone', phone)
        commit('setRenterPay', isRenterPay)
        sessionStorage.setItem('payWay',payWay)
        sessionStorage.setItem('phone',phone)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    removeToken() // must remove  token  first
    resetRouter()
    sessionStorage.clear()
    location.reload()
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

